package net.rlair.esAnalyzeWord.web;

import net.rlair.esAnalyzeWord.model.HotWord;
import net.rlair.esAnalyzeWord.service.EsClientService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * index.
 *
 * @author yaoyi
 * @version 1.0.0.0
 */
@Controller
@RequestMapping("/")
public class IndexController {

    /**
     * es服务.
     */
    @Resource
    private EsClientService esClientService;

    /**
     * 首页.
     *
     * @return view
     */
    @RequestMapping("/")
    @ResponseBody
    public String index() {
        return "hello esAnalyzeWord";
    }


    /**
     * 将分词加载到分析器中.
     * @param request request
     * @param response response
     * @return String.
     */
    @RequestMapping("/flushHotWord")
    @ResponseBody
    public String flushHotWord(final HttpServletRequest request, final HttpServletResponse response) {
        String result = "";
        final List<HotWord> wordList = esClientService.queryHotWord();
        if(CollectionUtils.isEmpty(wordList)){
            return result;
        }

        final StringBuilder sb = new StringBuilder();
        final String eTag = request.getHeader("If-None-Match");
        Long modified= request.getDateHeader("If-Modified-Since");

        //设置头
        if(null == modified || -1 == modified) {
            //如果没有，则使用当前时间
            modified = System.currentTimeMillis();
        }

        //设置头信息。
        final String oldEtag = wordList.size() + "_" + wordList.get(0).getId();
        response.setDateHeader("Last-Modified", Long.valueOf(modified));
        response.setHeader("ETags", oldEtag);

        if(!oldEtag.equals(eTag)) {
            final List<HotWord> newWords=new ArrayList<>();
            //拼装结果
            for(HotWord tempWord : wordList) {
                //分词之间以换行符连接
                if(StringUtils.isNotEmpty(sb.toString())) {
                    sb.append("\r\n");
                }
                //同步过的分词改变状态
                if("0".equals(tempWord.getStatus())){
                    tempWord.setStatus("1");
                    newWords.add(tempWord);
                }

                sb.append(tempWord.getWord());
            }
            result = sb.toString();
            //更新时间
            response.setDateHeader("Last-Modified", System.currentTimeMillis());

            if(CollectionUtils.isNotEmpty(newWords)){
                esClientService.saveOrUpdateBulk(wordList);
            }
        }
        return result;
    }

    /**
     * 创建数据类型.
     * @return 是否成功.
     */
    @RequestMapping("/createMap")
    @ResponseBody
    public boolean createMap() {
        esClientService.deleteAll();
        return esClientService.createMapping();
    }

    /**
     * 将分词加载到分析器中.
     * @param word word
     * @return 是否成功.
     */
    @RequestMapping("/addHotWord")
    @ResponseBody
    public boolean addHotWord(@RequestBody final HotWord word) {
        if(word !=null && StringUtils.isNotBlank(word.getWord())){
            word.setId(UUID.randomUUID().toString());
            word.setCreateTime(new Date());
            word.setStatus("0");
            final List<HotWord> words=new ArrayList<>();
            words.add(word);
            return esClientService.saveOrUpdateBulk(words);
        }
        return false;
    }

    /**
     * 将分词加载到分析器中.
     * @param word word
     * @return 是否成功.
     */
    @RequestMapping("/deleteHotWord")
    @ResponseBody
    public boolean deleteHotWord(@RequestBody final HotWord word) {
        if(word !=null && StringUtils.isNotBlank(word.getWord())){
            return esClientService.delete(word);
        }
        return false;
    }
}
